package tt.dz.egobus.servicemanager.business.listener.handler;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import tt.dz.egobus.api.ResponseBack;
import tt.dz.egobus.api.usercenter.user.UserInfoBack;
import tt.dz.egobus.servicemanager.bean.RedisTopicMessage;
import tt.dz.egobus.servicemanager.bean.SpringConfigConstant;
import tt.dz.egobus.servicemanager.business.listener.RedisEventMessageHandler;
import tt.dz.egobus.servicemanager.entities.Bus;
import tt.dz.egobus.servicemanager.entities.BusinessService;
import tt.dz.egobus.servicemanager.entities.BusinessServiceInfo;
import tt.dz.egobus.servicemanager.facade.common.CommonFacade;
import tt.dz.egobus.servicemanager.facade.interator.FacadeFactory;
import tt.dz.egobus.servicemanager.facade.interator.FacadeFactoryLoggerInterceptorHolder;
import tt.dz.egobus.servicemanager.facade.user.UserCenterFacade;
import tt.dz.egobus.servicemanager.service.BusService;
import tt.dz.egobus.servicemanager.service.BusinessServiceInfoService;
import tt.dz.egobus.servicemanager.util.DateUtils;

import java.util.Date;

/**
 * @author Anson
 * @date 17-9-1
 * @name 短信通知处理
 * @since 1.0.7
 */
public class MsgNotifyHandler implements RedisEventMessageHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(MsgNotifyHandler.class);

    //(梁小雨)你好，(陈总)为您预订的(8月17日9:30)(成都旅游集散地)出发(半日包车)已安排成功，(徐师傅)(13880136783)，车牌(川A60F8Q)为单总服务，请做好准备提前到达出发点。温馨提示：上车后请系好安全带
    private static final String PASSENGER_CONTENT =
            "%s你好，%s预订的%s%s出发%s已安排成功，%s%s，车牌(%s)为单总服务，请做好准备提前到达出发点。温馨提示：上车后请系好安全带";

    //(徐)师傅你好，(陈总为梁小雨)预订的(8月17日9:30)(成都旅游集散地)出发(半日包车)已安排成功，请您务必准时到达上车位置，为乘客提供车辆服务。温馨提示：上车后请系好安全带
    private static final String DRIVER_CONTENT =
            "%s师傅你好,%s预订的%s%s出发%s即将出发，请您务必准时到达上车位置，为乘客提供车辆服务。温馨提示：上车后请系好安全带";


    private static final String BUSINESS_NAME = "预约单行程";

    @Override
    public String id() {
        return SpringConfigConstant.BUSINESS_MSG_NOTIFY_KEY;
    }

    @Override
    public void handlerEvent(RedisTopicMessage redisTopicMessage,
                             RedisTemplate redisTemplate,
                             ApplicationContext applicationContext) {
        String businessId = redisTopicMessage.getBusinessKey();
        BusinessServiceInfoService businessServiceInfoService =
                applicationContext.getBean("businessServiceInfoServiceImpl", BusinessServiceInfoService.class);
        BusinessServiceInfo businessServiceInfo = businessServiceInfoService.getInfoByServiceId(businessId);
        if (businessServiceInfo == null) {
            return;
        }
        BusinessService businessService = businessServiceInfo.getBusinessService();
        if (businessService == null) {
            return;
        }
        this.sendMsg(businessService, businessServiceInfo, applicationContext);
    }

    private void sendMsg(BusinessService businessService, BusinessServiceInfo businessServiceInfo, ApplicationContext applicationContext) {
        FacadeFactory facadeFactory = FacadeFactoryLoggerInterceptorHolder.LOGGER_FACADE;
        CommonFacade commonFacade = facadeFactory.getBean("common", CommonFacade.class);
        BusService busService = applicationContext.getBean("busServiceImpl", BusService.class);
        Bus bus = busService.get(businessServiceInfo.getBusId());
        String busNo = "";
        if (bus != null) {
            busNo = bus.getCarNo();
        }
        //是不是自己用车
        boolean isSelf = businessService.getIsRideSelf();
        String passengerName = StringUtils.defaultString(businessServiceInfo.getPassengerName(), "匿名");
        String passengerPhone = StringUtils.defaultString(businessServiceInfo.getPassengerPhone(), "");
        String userName = StringUtils.defaultString(businessServiceInfo.getUserName(), "匿名");
        //String userPhone = businessServiceInfo.getUserPhone();
        String driverName = StringUtils.defaultString(businessServiceInfo.getDriverName(), "匿名");
        String requestAddress = StringUtils.defaultString(businessServiceInfo.getRequestStartAddress(), "");
        String serviceName = StringUtils.defaultString(businessServiceInfo.convertBusService().getName(), "");
        String driverPhone = "";
        Date bespeakDate = businessServiceInfo.getBespeakTime();
        if (bespeakDate == null) {
            return;
        }
        String bespeakDateStr = DateUtils.DateToString(bespeakDate,
                DateUtils.DATE_TO_STRING_DETAIAL_PATTERN_mm);
        UserCenterFacade userCenterFacade = facadeFactory.getBean("usercenter", UserCenterFacade.class);
        ResponseBack<UserInfoBack> userInfoBackResponseBack = userCenterFacade.findUserInfo(businessService.getDriverId());
        if (userInfoBackResponseBack != null && userInfoBackResponseBack.getResult() != null) {
            driverPhone = userInfoBackResponseBack.getResult().getPhoneNumber();
        }
        String driverSendMsg = this.wrapDriverMsgContent(driverName, bespeakDateStr, passengerName,
                userName, requestAddress, serviceName, isSelf);
        if (!StringUtils.isAnyEmpty(passengerPhone, driverSendMsg)) {
            commonFacade.sendInformNote(driverPhone, driverSendMsg, BUSINESS_NAME);
        }
        //用车人短信发送
        String passengerMsgContent = this.wrapUserMsgContent(driverName, driverPhone, bespeakDateStr, passengerName,
                userName, requestAddress, serviceName, isSelf, busNo);
        if (!StringUtils.isAnyEmpty(passengerPhone, passengerMsgContent)) {
            commonFacade.sendInformNote(passengerPhone, passengerMsgContent, BUSINESS_NAME);
        }
    }

    /**
     * @param driverName     司机名称
     * @param driverPhone    司机名称
     * @param bespeakDateStr 预约时间
     * @param passengerName  用车人
     * @param userName       预约人
     * @param requestAddress 请求上车地址
     * @param serviceName    服务名称
     * @param isSelf         是否自己用车
     * @author Anson
     * @date 17-9-2
     * @name 封装乘车人预约通知信息
     * @since 1.0.7
     */
    private String wrapUserMsgContent(String driverName, String driverPhone, String bespeakDateStr,
                                      String passengerName, String userName,
                                      String requestAddress, String serviceName,
                                      boolean isSelf, String busNo) {
        String passageInfo = isSelf ? passengerName : userName + "为" + passengerName;
        String driverInfo = driverName;
        return String.format(PASSENGER_CONTENT, passengerName, passageInfo, bespeakDateStr, requestAddress, serviceName,
                driverInfo, driverPhone, busNo);
    }

    /**
     * @param driverName     司机名称
     * @param bespeakDateStr 预约时间
     * @param passengerName  用车人
     * @param userName       预约人
     * @param requestAddress 请求上车地址
     * @param serviceName    服务名称
     * @param isSelf         是否自己用车
     * @author Anson
     * @date 17-9-1
     * @name 封装司机预约提醒
     * @since 1.0.7
     */
    private String wrapDriverMsgContent(String driverName, String bespeakDateStr, String passengerName, String userName,
                                        String requestAddress, String serviceName, boolean isSelf) {
        String passageInfo = isSelf ? passengerName : userName + "为" + passengerName;
        return String.format(DRIVER_CONTENT, driverName, passageInfo, bespeakDateStr, requestAddress, serviceName);
    }


}
